<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox, ElDrawer } from "element-plus";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import {
  addArticleCategory,
  updateArticleCategory,
  delArticleCategory,
  getArticleCategoryDetail,
  getArticleCategoryTree // 导入 getArticleCategoryTree
} from "@/api/article-category";
import CategoryForm from "./form.vue";

defineOptions({
  name: "ArticleCategory"
});

const formRef = ref();
const tableRef = ref();
const drawerVisible = ref(false);
const drawerTitle = ref("");
const expandLevel = ref(1); // 新增：展开层级控制
const categoryFormRef = ref<InstanceType<typeof CategoryForm>>(); // Added type for ref
const formKey = ref(0); // 添加 key 用于强制重新渲染组件

const initialFormData = {
  id: undefined,
  name: "",
  parent_id: null,
  sort: 0,
  icon: "",
  is_displayed: 0, // 默认显示状态为 0（不显示）
  sort_order: 0
};

// 抽屉关闭时的处理
const handleDrawerClose = (done: () => void) => {
  // 关闭时完全重置表单数据和状态
  Object.assign(formData, JSON.parse(JSON.stringify(initialFormData)));
  formKey.value++;
  console.log("抽屉关闭 - 表单数据已重置:", JSON.stringify(formData));
  done();
};

// 重置表单的核心方法
const resetFormData = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    delete formData[key];
  });
  Object.assign(formData, JSON.parse(JSON.stringify(initialFormData)));

  // 强制重新渲染组件
  formKey.value++;
};

const formData = reactive({ ...initialFormData }); // 初始化 formData

const form = reactive({
  name: ""
});
const loading = ref(false);
const dataList = ref([]);
const originalDataList = ref([]); // 新增：存储原始树形数据
const selectedNum = ref(0);
const selectedRows = ref([]); // 用于批量删除

// 树形表格展开/折叠逻辑
const handleExpandLevelChange = level => {
  const table = tableRef.value;
  if (!table) return;

  const expand = (rows, level) => {
    rows.forEach(row => {
      if (level > 0) {
        table.toggleRowExpansion(row, true);
        if (row.children) {
          expand(row.children, level - 1);
        }
      } else {
        table.toggleRowExpansion(row, false);
      }
    });
  };

  const collapseAll = rows => {
    rows.forEach(row => {
      table.toggleRowExpansion(row, false);
      if (row.children) {
        collapseAll(row.children);
      }
    });
  };

  const expandAll = rows => {
    rows.forEach(row => {
      table.toggleRowExpansion(row, true);
      if (row.children) {
        expandAll(row.children);
      }
    });
  };

  if (level === 0) {
    collapseAll(dataList.value); // 使用 dataList.value
  } else if (level === -1) {
    expandAll(dataList.value); // 使用 dataList.value
  } else {
    collapseAll(dataList.value); // 使用 dataList.value
    expand(dataList.value, level); // 使用 dataList.value
  }
};

// 获取文章分类列表 (树形结构)
const getList = async () => {
  loading.value = true;
  try {
    console.log("开始获取文章分类列表...");
    const { code, data, message } = await getArticleCategoryTree(); // 调用获取树形结构的接口
    console.log("获取文章分类列表响应:", { code, message, data });
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    originalDataList.value = data; // 存储原始数据
    dataList.value = data; // 初始显示全部数据
    console.log("文章分类列表数据已更新:", dataList.value);
  } catch (e) {
    ElMessage.error("获取文章分类列表失败");
    console.error("获取文章分类列表错误:", e);
  } finally {
    loading.value = false;
    console.log("获取文章分类列表结束.");
  }
};

// 递归过滤树形数据
const filterTree = (tree: any[], keyword: string) => {
  if (!keyword) return tree;
  return tree
    .filter(node => {
      const matches = node.name.includes(keyword);
      let childrenMatch = false;
      let newChildren: any[] = [];

      if (node.children && node.children.length > 0) {
        newChildren = filterTree(node.children, keyword);
        if (newChildren.length > 0) {
          childrenMatch = true;
        }
      }

      if (matches || childrenMatch) {
        const newNode = { ...node }; // 创建新节点副本
        newNode.children = newChildren; // 赋值过滤后的子节点
        return newNode;
      }
      return false; // 不匹配则不保留
    })
    .filter(Boolean); // 过滤掉 false 值
};

const onSearch = async () => {
  // 重新从后端获取数据
  await getList();
  if (form.name) {
    dataList.value = filterTree(originalDataList.value, form.name);
  } else {
    // 如果没有搜索关键字，getList 已经将 originalDataList 赋值给 dataList，
    // 此时恢复默认展开层级即可
    nextTick(() => handleExpandLevelChange(expandLevel.value));
  }
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

// 批量删除
const onbatchDel = () => {
  if (selectedNum.value === 0) {
    ElMessage.warning("请选择要删除的文章分类");
    return;
  }
  ElMessageBox.confirm(`是否确认删除选中的 ${selectedNum.value} 篇文章分类？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const ids = selectedRows.value.map(row => row.id);
    const { code, message, failed_categories } = await delArticleCategory({
      ids
    });
    console.log("批量删除文章分类响应:", { code, message, failed_categories });
    if (code === 200) {
      ElMessage.success(message || "批量删除成功");
      console.log("调用 onSearch() 刷新列表 (批量删除)");
      onSearch();
    } else {
      ElMessage.error(message);
    }
  });
};

// 单条删除
const handleDelete = row => {
  ElMessageBox.confirm(`是否确认删除分类名称为${row.name}的这条数据`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const { code, message, failed_categories } = await delArticleCategory({
      ids: [row.id]
    }); // 修改为传递数组
    console.log("删除单条文章分类响应:", { code, message, failed_categories });
    if (code === 200) {
      ElMessage.success(message || "删除成功");
      console.log("调用 onSearch() 刷新列表 (单条删除)");
      onSearch();
    } else {
      ElMessage.error(message);
    }
  });
};

const handleSelectionChange = val => {
  selectedNum.value = val.length;
  selectedRows.value = val; // 存储选中的行数据
};
// 打开抽屉
const openDrawer = async (title = "新增", row?: any) => {
  drawerTitle.value = title;

  // 1. 重置表单数据
  resetFormData();

  // 2. 如果是修改操作，从后端获取完整详情
  if (row && title === "修改") {
    try {
      console.log("修改模式 - 获取分类详情, ID:", row.id);
      const { code, data, message } = await getArticleCategoryDetail({
        id: row.id
      });
      if (code === 200) {
        // 使用深拷贝避免引用问题
        const detailData = JSON.parse(JSON.stringify(data));
        Object.assign(formData, detailData);
        console.log("修改模式 - 详情数据已加载:", JSON.stringify(formData));
      } else {
        ElMessage.error(message || "获取分类详情失败");
        return; // 获取失败则不打开抽屉
      }
    } catch (error) {
      ElMessage.error("获取分类详情失败");
      console.error("获取详情错误:", error);
      return;
    }
  } else if (row && title === "新增下级") {
    // 新增下级模式：设置当前行的ID作为新分类的父级ID
    formData.parent_id = row.parent_id; // 这里接收的是模板传递的 { parent_id: row.id }
    console.log("新增下级模式 - parent_id已设置:", formData.parent_id);
  }

  // 3. 打开抽屉
  drawerVisible.value = true;
};
// 提交表单
const handleSubmit = async (data: any) => {
  console.log("步骤表单数据", data);

  try {
    let res;
    if (data.id) {
      res = await updateArticleCategory(data);
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return;
      }
      ElMessage.success("更新成功");
    } else {
      // Handle potential null parent_id for new categories
      if (data.parent_id === null) {
        data.parent_id = 0;
      }
      res = await addArticleCategory(data);
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return;
      }
      ElMessage.success("新增成功");
    }

    // 提交成功后关闭抽屉
    drawerVisible.value = false;
    await getList();
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

import { nextTick, watch } from "vue"; // 导入 nextTick 和 watch

onMounted(() => {
  getList();
});

watch(
  [dataList, expandLevel], // 同时监听“树数据”和“展开层级”
  ([tree, level]) => {
    if (tree.length) {
      // 数据已经有了
      nextTick(() => handleExpandLevelChange(level));
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="分类名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" clearable class="w-[180px]!" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri/search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)"> 重置 </el-button>
      </el-form-item>
    </el-form>

    <div class="p-4 bg-bg_color">
      <div class="flex justify-between items-center mb-4">
        <p class="font-bold">文章分类列表</p>
        <div class="flex items-center">
          <el-select
            v-model="expandLevel"
            placeholder="展开层级"
            style="width: 120px; margin-right: 10px"
            @change="handleExpandLevelChange"
          >
            <el-option label="全部折叠" :value="0" />
            <el-option label="展开1层" :value="1" />
            <el-option label="展开2层" :value="2" />
            <el-option label="展开3层" :value="3" />
            <el-option label="展开4层" :value="4" />
            <el-option label="全部展开" :value="-1" />
          </el-select>
          <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDrawer('新增')">
            新增分类
          </el-button>
          <el-button
            type="danger"
            :icon="useRenderIcon(Delete)"
            :disabled="selectedNum === 0"
            @click="onbatchDel"
          >
            批量删除
          </el-button>
        </div>
      </div>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="dataList"
        row-key="id"
        default-expand-all
        :default-sort="{ prop: 'sort_order', order: 'ascending' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分类名称" prop="name" />
        <el-table-column label="排序" prop="sort_order" width="80" sortable />
        <el-table-column label="分类图标" prop="icon" width="100" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="useRenderIcon(row.icon)" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="是否显示" prop="is_displayed" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_displayed ? 'success' : 'info'">
              {{ row.is_displayed ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" :icon="useRenderIcon(EditPen)" @click="openDrawer('修改', row)">
              修改
            </el-button>
            <el-button
              link
              type="primary"
              :icon="useRenderIcon(AddFill)"
              @click="openDrawer('新增下级', { parent_id: row.id })"
            >
              新增下级
            </el-button>
            <el-button link type="danger" :icon="useRenderIcon(Delete)" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--抽屉-->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="60%" :before-close="handleDrawerClose">
      <template #title>
        <div class="flex justify-between items-center">
          <p class="font-bold">{{ drawerTitle }}</p>
          <el-button type="text" @click="drawerVisible = false" />
        </div>
      </template>
      <CategoryForm
        :key="formKey"
        ref="categoryFormRef"
        :form-inline="formData"
        :category-tree-data="dataList"
        @submit="handleSubmit"
      />
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerVisible = false">取 消</el-button>
          <el-button type="primary" @click="categoryFormRef.submitForm()">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
